import React, {useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {Avatar, Button, Card, Divider, Form, Input, message, Tabs, Typography} from 'antd';
import {useModel} from '@umijs/max';
import {deactivateAccount, getUserInfo, updatePassword, updateProfile} from '@/services/ant-design-pro/userController';
import {LockOutlined, MailOutlined, PhoneOutlined, UserOutlined} from '@ant-design/icons';
import styles from './index.less';

const {Title, Paragraph, Text} = Typography;
const {TabPane} = Tabs;

const UserProfile: React.FC = () => {
  const {initialState, setInitialState} = useModel('@@initialState');
  const {currentUser} = initialState || {};

  const [basicForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [basicLoading, setBasicLoading] = useState<boolean>(false);
  const [passwordLoading, setPasswordLoading] = useState<boolean>(false);
  const [deactivateLoading, setDeactivateLoading] = useState<boolean>(false);

  // 更新用户基本信息
  const handleUpdateBasic = async (values: API.UserUpdateProfileDTO) => {
    setBasicLoading(true);
    try {
      const res = await updateProfile(values);
      if (res.code === 0 && res.data) {
        message.success('个人信息更新成功');

        // 更新全局用户信息
        setInitialState((oldState) => ({
          ...oldState,
          currentUser: res.data,
        }));

        // 重新加载用户信息
        const userInfo = await getUserInfo();
        if (userInfo.data) {
          setInitialState((oldState) => ({
            ...oldState,
            currentUser: userInfo.data,
          }));
        }
      } else {
        message.error('个人信息更新失败');
      }
    } catch (error) {
      message.error('个人信息更新失败');
    } finally {
      setBasicLoading(false);
    }
  };

  // 更新密码
  const handleUpdatePassword = async (values: API.UserUpdatePasswordDTO) => {
    setPasswordLoading(true);
    try {
      // 验证新密码与确认密码是否一致
      if (values.newPassword !== values.confirmPassword) {
        message.error('两次输入的新密码不一致');
        return;
      }

      const res = await updatePassword(values);
      if (res.code === 0 && res.data) {
        message.success('密码修改成功');
        passwordForm.resetFields();
      } else {
        message.error('密码修改失败');
      }
    } catch (error) {
      message.error('密码修改失败');
    } finally {
      setPasswordLoading(false);
    }
  };

  // 注销账号
  const handleDeactivate = async () => {
    if (!window.confirm('确定要注销账号吗？此操作不可逆！')) {
      return;
    }

    setDeactivateLoading(true);
    try {
      const res = await deactivateAccount();
      if (res.code === 0 && res.data) {
        message.success('账号已注销');
        // 清空用户信息并重定向到登录页
        setInitialState((oldState) => ({
          ...oldState,
          currentUser: undefined,
        }));
        window.location.href = '/user/login';
      } else {
        message.error('账号注销失败');
      }
    } catch (error) {
      message.error('账号注销失败');
    } finally {
      setDeactivateLoading(false);
    }
  };

  return (
    <PageContainer
      header={{
        title: '个人资料',
        breadcrumb: {},
        ghost: true,
      }}
    >
      <div className={styles.container}>
        <Card className={styles.card}>
          <div className={styles.userInfo}>
            <Avatar
              size={80}
              icon={<UserOutlined/>}
              src={currentUser?.avatar}
              className={styles.avatar}
            />
            <div className={styles.userMeta}>
              <Title level={4}>{currentUser?.username || '用户'}</Title>
              <Text type="secondary">账号: {currentUser?.account}</Text>
            </div>
          </div>

          <Divider/>

          <Tabs defaultActiveKey="basic">
            <TabPane tab="基本信息" key="basic">
              <Form
                form={basicForm}
                layout="vertical"
                initialValues={{
                  username: currentUser?.username,
                  email: currentUser?.email,
                  phone: currentUser?.phone,
                  avatar: currentUser?.avatar,
                }}
                onFinish={handleUpdateBasic}
              >
                <Form.Item
                  label="用户名"
                  name="username"
                  rules={[{required: true, message: '请输入用户名'}]}
                >
                  <Input prefix={<UserOutlined/>}/>
                </Form.Item>

                <Form.Item
                  label="邮箱"
                  name="email"
                  rules={[
                    {required: false},
                    {type: 'email', message: '请输入有效的邮箱地址'}
                  ]}
                >
                  <Input prefix={<MailOutlined/>}/>
                </Form.Item>

                <Form.Item
                  label="手机号"
                  name="phone"
                >
                  <Input prefix={<PhoneOutlined/>}/>
                </Form.Item>

                <Form.Item
                  label="头像URL"
                  name="avatar"
                >
                  <Input/>
                </Form.Item>

                <Form.Item>
                  <Button type="primary" htmlType="submit" loading={basicLoading}>
                    保存修改
                  </Button>
                </Form.Item>
              </Form>
            </TabPane>

            <TabPane tab="修改密码" key="password">
              <Form
                form={passwordForm}
                layout="vertical"
                onFinish={handleUpdatePassword}
              >
                <Form.Item
                  label="当前密码"
                  name="oldPassword"
                  rules={[{required: true, message: '请输入当前密码'}]}
                >
                  <Input.Password prefix={<LockOutlined/>}/>
                </Form.Item>

                <Form.Item
                  label="新密码"
                  name="newPassword"
                  rules={[{required: true, message: '请输入新密码'}]}
                >
                  <Input.Password prefix={<LockOutlined/>}/>
                </Form.Item>

                <Form.Item
                  label="确认新密码"
                  name="confirmPassword"
                  rules={[
                    {required: true, message: '请确认新密码'},
                    ({getFieldValue}) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('newPassword') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('两次输入的密码不一致'));
                      },
                    }),
                  ]}
                >
                  <Input.Password prefix={<LockOutlined/>}/>
                </Form.Item>

                <Form.Item>
                  <Button type="primary" htmlType="submit" loading={passwordLoading}>
                    修改密码
                  </Button>
                </Form.Item>
              </Form>
            </TabPane>

            <TabPane tab="账号安全" key="security">
              <div className={styles.securitySection}>
                <Title level={5}>注销账号</Title>
                <Paragraph type="secondary">
                  注销账号后，您的所有数据将被删除，且无法恢复。请谨慎操作。
                </Paragraph>
                <Button
                  danger
                  onClick={handleDeactivate}
                  loading={deactivateLoading}
                >
                  注销账号
                </Button>
              </div>
            </TabPane>
          </Tabs>
        </Card>
      </div>
    </PageContainer>
  );
};

export default UserProfile;
